import { useContext } from 'react';
import FlowEditorContext from '../../FlowEditor/FlowEditorContext';

function useEditorAPI() {
  const { propsAPI } = useContext(FlowEditorContext);
  const { getSelected, executeCommand, update, save, remove } = propsAPI;

  let success = true;
  try {
    getSelected();
  } catch (e) {
    success = false;
  }

  if (!success) {
    return {};
  }

  const getItem = () => getSelected()[0];

  const wrappedUpdate = payload => {
    const item = getItem();
    executeCommand(() => {
      update(item, payload);
    });
  };

  const wrappedRemove = () => {
    const item = getItem();
    executeCommand(() => {
      remove(item);
    });
  };

  return {
    update: wrappedUpdate,
    remove: wrappedRemove,
    getSelected: () => {
      const item = getItem() || {};
      return item.model;
    },
    getNodes: () => {
      const graph = save() || {};
      return graph.nodes || [];
    },
  };
}

export default useEditorAPI;
